package com.base.library.base

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import com.base.library.utils.LogUtils

data class ActivityStarterResult(
    var intent: Intent?,
    val code: Int = 0
) {
    fun startActivityForResult(context: Context) {
        try {
            val intent = intent ?: return
            this.intent = null
            intent.component?.also {
                if (it.packageName.isEmpty()) {
                    intent.component = ComponentName(context.packageName, it.className)
                }
            }

            if (context is Activity) {
                context.startActivityForResult(intent, code)
            } else {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
            }
        } catch (e: Exception) {
            LogUtils.e("startActivityForResult", e)
        }
    }

    fun startActivityForResult(fragment: Fragment) {
        try {
            val intent = intent ?: return
            this.intent = null
            val activity = fragment.activity
            activity ?: return

            intent.component?.also {
                if (it.packageName.isEmpty()) {
                    intent.component = ComponentName(activity.packageName, it.className)
                }
            }

            fragment.startActivityForResult(intent, code)
        } catch (e: Exception) {
            LogUtils.e("startActivityForResult", e)
        }
    }

    override fun toString(): String {
        return "ActivityStarterResult(intent=$intent, code=$code)"
    }
}